<?php

class html {
	
	/**
	 * Creates a image tag.
	 * Base will be added automaticly.
	 * @param   string        image source, or an array of attributes
	 * @param   string|array  image alt attribute, or an array of attributes
	 * @return  string
	 */
	public static function img($src = NULL, $alt = NULL) {
		// Create attribute list
		$attributes = is_array ( $src ) ? $src : array ('src' => $src );
		
		if (is_array ( $alt ))
			$attributes += $alt;
		elseif (! empty ( $alt ))
			$attributes ['alt'] = $alt;
		
		if (! isset ( $attributes ['alt'] ))
			$attributes ['alt'] = '';
		if (strpos ( $attributes ['src'], '://' ) === FALSE) {
			// Make the src attribute into an absolute URL
			$attributes ['src'] = url::base () . $attributes ['src'];
		}
		
		return '<img' . html::attributes ( $attributes ) . ' />';
	}
	
	/**
	 * Create HTML link.
	 * Base will be added automaticly.
	 * @param   string  URL or URI string
	 * @param   string  link text
	 * @param   array   HTML anchor attributes
	 * @return  string
	 */
	public static function a($uri, $body = NULL, $attributes = NULL) {
		return '<a href="' . html::specialchars ( url::link ( $uri ), false ) . '"' . (is_array ( $attributes ) ? html::attributes ( $attributes ) : '') . '>' . (($body === NULL) ? url::link ( $uri ) : $body) . '</a>';
	}
	
	/**
	 * Create attributes from an array of HTML attributes.
	 *
	 * @param   string|array  array of attributes
	 * @return  string
	 */
	protected static function attributes($attributes) {
		if (empty ( $attributes ))
			return '';
		
		if (is_string ( $attributes ))
			return ' ' . $attributes;
		
		$ret = '';
		foreach ( $attributes as $key => $val )
			$ret .= ' ' . $key . '="' . $val . '"';
		
		return $ret;
	}
	
	public static function specialchars($val, $double_encode = true) {
		$val = ( string ) $val;
		if ($double_encode === true)
			$val = htmlspecialchars ( $val, ENT_QUOTES, 'UTF-8' );
		else {
			if (version_compare ( PHP_VERSION, '5.2.3', '>=' )) {
				$val = htmlspecialchars ( $val, ENT_QUOTES, 'UTF-8', false );
			} else {
				$val = preg_replace ( '/&(?!(?:#\d++|[a-z]++);)/ui', '&amp;', $val );
				$val = str_replace ( array ('<', '>', '\'', '"' ), array ('&lt;', '&gt;', '&#39;', '&quot;' ), $val );
			}
		}
		return $val;
	}
}

?>